<template>
  <div class="all-incident-wrapper">
    <p class="title">综合条件查询</p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="事件名称">
          <el-input v-model="formInline.eventNameLike" placeholder="请输入事件名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="发生日期">
          <el-date-picker
            v-model="formInline.occurDate"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="事件规模">
          <el-select v-model="formInline.eventSize" placeholder="请选择事件规模" clearable>
            <el-option
              v-for="(item) in optList.eventSize"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件类别">
          <el-input v-model="formInline.eventType" placeholder="请输入事件类别" clearable></el-input>
        </el-form-item>
        <el-form-item label="事件办理进度">
          <el-select v-model="formInline.eventStatus" placeholder="请选择事件办理进度" clearable>
            <el-option
              v-for="(item) in optList.eventStatus"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增</el-button>
        <el-button size="medium">导入</el-button>
        <el-button size="medium" @click="exportTable">导出</el-button>
        <el-button size="medium" @click="batchDeletion">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="事件名称" prop="eventName"></el-table-column>
        <el-table-column label="发生日期" prop="happenDate"></el-table-column>
        <el-table-column label="发生地点" prop="happenPlace"></el-table-column>
        <el-table-column label="事件规模" prop="eventSize">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.eventSize, optList.eventSize)}}</template>
        </el-table-column>
        <el-table-column label="事件类别" prop="eventType"></el-table-column>
        <el-table-column label="是否指派" prop="assign">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.assign, optList.yesOrNo)}}</template>
        </el-table-column>
        <el-table-column label="化解责任人姓名" prop="resolveName"></el-table-column>
        <el-table-column label="事件办理进度" prop="eventStatus">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.eventStatus, optList.eventStatus)}}</template>
        </el-table-column>
        <el-table-column label="操作" min-width="100">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.id)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        @current-change="pageChange"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="矛盾纠纷事件" :visible.sync="dialogFormVisible" width="840px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">

        <el-row>
          <el-col :span="spanGrid(field)" v-for="(field, index) in allFields" :key="index">
            <el-form-item :label="field.fieldTxt" label-width="180px" :prop="field.fieldName">
              <el-input v-if="field.UiType===1" v-model="dialogForm[field.fieldName]" :placeholder="field.placeholder" autocomplete="off" clearable></el-input>
              <el-input v-if="field.UiType===4" v-model="dialogForm[field.fieldName]" :placeholder="field.placeholder" autocomplete="off" clearable type="textarea"></el-input>
              <el-select
               v-if="field.UiType===2||field.UiType===21"
               v-model="dialogForm[field.fieldName]"
               :placeholder="field.placeholder"
               clearable
               :multiple="field.UiType===21">
                <el-option
                  v-for="(item) in getOptions(field)"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <el-select
               v-if="field.UiType===22"
               v-model="dialogForm[field.fieldName]"
               :placeholder="field.placeholder"
               clearable>
               <el-option-group
                v-for="(item) in getOptions(field)"
                :key="item.code"
                :label="item.name">
                 <el-option
                    v-for="(subItem) in item[field.fieldName]"
                    :key="subItem.code"
                    :label="subItem.name"
                    :value="subItem.code">
                  </el-option>
               </el-option-group>
              </el-select>
              <el-date-picker v-if="field.UiType===3"
                v-model="dialogForm[field.fieldName]"
                type="date"
                :placeholder="field.placeholder"
                clearable>
              </el-date-picker>
              <el-date-picker v-if="field.UiType===31"
                v-model="dialogForm[field.fieldName]"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
              <el-upload v-if="field.fieldName==='picture'"
                class="upload-demo"
                :file-list="fileListPic"
                :ref="field.fieldName"
                :action="uploadUrl"
                :before-upload="beforePicUpload"
                :on-success="uploadPicSuccess"
                :on-preview="handlePicPreview"
                :on-remove="handlePicRemove"
                :limit="1"
                :on-exceed="handleExceed">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
              <el-upload v-if="field.fieldName==='video'"
                class="upload-demo"
                :file-list="fileListVideo"
                :ref="field.fieldName"
                :action="uploadUrl"
                :before-upload="beforeVideoUpload"
                :on-success="uploadVideoSuccess"
                :on-preview="handleVideoPreview"
                :on-remove="handleVideoRemove"
                :limit="1"
                :on-exceed="handleExceed">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传mp4视频文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getGovernDisputeList,
  addGovernDispute,
  getGovernDisputeDetail,
  updateGovernDisputeDetail,
  deleteGovernDispute,
  deleteGovernDisputeBatch
  // exportGovernOrgan
} from '@/api/baseBusiness'
import { deepClone, convertDateToString } from '@/utils'
import { mapState } from 'vuex'

import { allFields, optList } from './disputeFields'

export default {
  name: 'AllIncident',
  data () {
    return {
      allFields,
      optList,
      formInline: {
        eventNameLike: '',
        occurDate: '',
        eventSize: '',
        eventType: '',
        eventStatus: ''
      },
      loading: false,
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      dialogForm: {
      },
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      totalCount: 0, // 总共多少条
      currentPage: 1, // 分页当前页
      rules: {
      },
      uploadingFilesNum: 0,
      uploadUrl: `${process.env.VUE_APP_BASE_API}/upload-service/upload/uploadFile`,
      fileListPic: [],
      fileListVideo: []
    }
  },
  computed: {
    ...mapState([
      'areaId'
    ]),
    ruleFields () {
      return this.allFields.filter(obj => obj.must)
    }
  },
  methods: {
    beforePicUpload (file) {
      return this.beforeUpload(file, 'picture')
    },
    beforeVideoUpload (file) {
      return this.beforeUpload(file, 'video')
    },
    beforeUpload (file, fieldName) {
      if (fieldName === 'picture') {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJPGOrPNG) {
          this.$message.error('图片只能上传jpg/png格式!')
        } else {
          this.uploadingFilesNum += 1
        }
        return isJPGOrPNG
      } else if (fieldName === 'video') {
        const isMP4 = file.type === 'video/mp4'
        if (!isMP4) {
          this.$message.error('只能上传mp4视频格式!')
        } else {
          this.uploadingFilesNum += 1
        }
        return isMP4
      }
    },
    uploadPicSuccess (response, file, fileList) {
      this.uploadSuccess(response, file, fileList, 'picture')
    },
    uploadVideoSuccess (response, file, fileList) {
      this.uploadSuccess(response, file, fileList, 'video')
    },
    uploadSuccess (response, file, fileList, fieldName) {
      this.uploadingFilesNum -= 1
      if (response.code === '200000') {
        this.$set(this.dialogForm, fieldName, response.data.fileId)
      }
    },
    handlePicPreview (file) {
      this.handlePreview(file, 'picture')
    },
    handleVideoPreview (file) {
      this.handlePreview(file, 'video')
    },
    handlePreview (file, fileName) {
      // 点击文件列表中已上传的文件时的钩子
      window.location.href = `${process.env.VUE_APP_BASE_API}/upload-service/upload/download?fileId=${this.dialogForm[fileName]}&token=nyyj`
    },
    handlePicRemove (file, fileList) {
      // 文件列表移除文件时的钩子
      this.handleRemove(file, fileList, 'picture')
    },
    handleVideoRemove (file, fileList) {
      // 文件列表移除文件时的钩子
      this.handleRemove(file, fileList, 'video')
    },
    handleRemove (file, fileList, fieldName) {
      if (file.status === 'uploading') {
        this.uploadingFilesNum -= 1
      }
      this.$set(this.dialogForm, fieldName, '')
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制上传 1 个文件`)
    },
    initDialogForm (arr = []) {
      arr.forEach((obj) => {
        this.$set(this.dialogForm, obj.fieldName, '')
      })
    },
    initRules () {
      this.ruleFields.forEach((obj) => {
        if (obj.UiType === 1 || obj.UiType === 4) {
          this.$set(this.rules, obj.fieldName, [{ required: true, message: obj.placeholder, trigger: 'blur' }])
        } else {
          this.$set(this.rules, obj.fieldName, [{ required: true, message: obj.placeholder, trigger: 'change' }])
        }
      })
    },
    spanGrid (field) {
      if (field.UiType === 4 || field.UiType === 31) {
        return 24
      }
      return 12
    },
    getOptions (field) {
      if (field.fieldName === 'partySex') {
        return this.DICY.sex
      }
      if (field.fieldName === 'partyNation') {
        return this.DICY.nation
      }
      if (field.fieldName === 'partyEducation') {
        return this.DICY.education
      }
      let bool = ['resolveSuccess', 'assign', 'filed']
      if (bool.includes(field.fieldName)) {
        return this.optList.yesOrNo
      }
      return this.optList[field.fieldName]
    },
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.code === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    searchOrg () {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch () {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    pageChange (curPage) {
      this.currentPage = curPage
      this.getOrgListAndShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
      console.log(this.$refs)
    },
    // 新增或修改机构
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          convertDateToString(requestData)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.areaId = this.areaId
            addGovernDispute(requestData).then((res) => {
              this.$message({
                message: '新增机构成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updateGovernDisputeDetail(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          areaId: this.areaId,
          ...deepClone(this.formInline)
        }
        var res = await getGovernDisputeList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
      this.fileListPic = []
      this.fileListPic.push({
        name: this.dialogForm.picture,
        url: ''
      })
      this.fileListVideo = []
      this.fileListVideo.push({
        name: this.dialogForm.video,
        url: ''
      })
    },
    viewDetail (id) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getGovernDisputeDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      getGovernDisputeDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteGovernDispute({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    batchDeletion () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选要删除的项!'
        })
      } else {
        var ids = this.multipleSelection.map((item) => {
          return item.id
        }).join(',')
        this.$confirm('确定删除, 是否继续?', '批量删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteGovernDisputeBatch({ ids }).then((res) => {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getOrgListAndShow()
          })
        })
      }
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
      this.$refs.picture[0].clearFiles()
      this.$refs.video[0].clearFiles()
    },
    exportTable () {
      // exportGovernOrgan({
      //   areaId: this.areaId,
      //   options: 'organName',
      //   titles: '机构名称'
      // }).then((res) => {
      //   console.log(res)
      //   var blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      //   var objectUrl = URL.createObjectURL(blob)
      //   var a = document.createElement('a')
      //   document.body.appendChild(a)
      //   a.style = 'display: none'
      //   a.href = objectUrl
      //   a.download = '综治机构' + parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')
      //   a.click()
      //   document.body.removeChild(a)
      //   this.$message({
      //     message: '导出成功',
      //     type: 'success'
      //   })
      // })
    }
  },
  created () {
    this.initDialogForm(allFields)
    this.initRules()
  },
  mounted () {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.all-incident-wrapper {
  background-color: #ffffff;
  margin-top: 20px;
  border-radius: 4px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  padding: 20px;
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .right-btn-area {
      height: 58px;
    }
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
      .el-date-editor--daterange.el-input__inner {
        width: 100%;
      }
    }
  }
}
</style>
